<template>
  <div class="product-add">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>添加新商品</span>
          <el-button @click="handleBack">
            <el-icon><ArrowLeft /></el-icon>
            返回列表
          </el-button>
        </div>
      </template>
      
      <ProductAddForm
        ref="formRef"
        :loading="submitLoading"
        @submit="handleSubmit"
        @cancel="handleCancel"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import ProductAddForm from '@/components/product/ProductAddForm.vue'
import { addProductApi, type ProductAddRequest } from '@/api/product'

const router = useRouter()
const formRef = ref()
const submitLoading = ref(false)

// 提交表单
const handleSubmit = async (formData: ProductAddRequest) => {
  try {
    submitLoading.value = true
    const response = await addProductApi(formData)
    
    if (response.code === 200) {
      ElMessage.success('商品添加成功')
      router.push('/product/list')
    } else {
      ElMessage.error(response.message || '添加失败')
    }
  } catch (error: any) {
    console.error('添加商品失败:', error)
    ElMessage.error(error.message || '添加失败，请重试')
  } finally {
    submitLoading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  router.push('/product/list')
}

// 返回列表
const handleBack = () => {
  router.push('/product/list')
}
</script>

<style lang="scss" scoped>
.product-add {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    span {
      font-size: 18px;
      font-weight: 500;
    }
  }
}
</style>

